<template>
  <div>
    <h2>监听数据变化后滚动到底部</h2>
    <div class="infro">
      <input type="text" v-model.trim="Inputtext" />
      <button @click="addMessage">添加信息</button>
    </div>
    <div ref="messageBox" class="messafe-box">
      <div v-for="mes in message" :key="mes.id">{{ mes.text }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onUpdated, ref } from 'vue'

const message = ref([
  { id: 1, text: 'Hello' },
  { id: 2, text: 'World' }
])

const Inputtext = ref('')
const addMessage = () => {
  message.value.push({ id: message.value.length + 1, text: Inputtext.value || '新的消息' })
}

const messageBox = ref()

onUpdated(() => {
  // 数据更新后滚到底部
  if (messageBox.value) {
    messageBox.value.scrollTop = messageBox.value.scrollHeight
  }
})
</script>

<style lang="scss" scoped>
.messafe-box {
  overflow-y: auto;
  height: 100px;
  border: 2px solid #ccc;
}
.infro {
  margin: 10px 0;
}
</style>
